<template>
  <a-spin
      :loading="spinLoading"
      :size="35"
      class="w-[100%]"
      tip="正在处理, 请稍候..."
  >
    <div class="edit-container">
      <h2 class="edit-title">新增交易申请</h2>

      <a-form
          ref="formRef"
          :label-col-props="{ span: 6 }"
          :model="form"
          :rules="rules"
          :wrapper-col-props="{ span: 18 }"
          class="edit-form"
          label-align="right"
      >
        <!-- 基本信息分组 -->
        <div class="form-section">
          <div class="form-section-title">基本信息</div>

          <a-form-item field="enterpriseAccountId" label="企业账号" required>
            <a-select
                v-model="form.enterpriseAccountId"
                allow-clear
                placeholder="请选择企业账号"
            >
              <a-option
                  v-for="item in enterpriseList"
                  :key="item.enterpriseName"
                  :value="item.enterpriseAccountId"
              >
                {{ item.enterpriseName }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="projectName" label="项目名称" required>
            <a-input
                v-model="form.projectName"
                placeholder="请输入项目名称"
            />
          </a-form-item>

          <a-form-item field="projectLocation" label="项目地址" required>
            <a-input
                v-model="form.projectLocation"
                placeholder="请输入项目地址"
            />
          </a-form-item>

          <a-form-item field="projectType" label="项目类型">
            <a-select
                v-model="form.projectType"
                allow-clear
                placeholder="请选择项目类型"
            >
              <a-option
                  v-for="(item,index) in dicts[proxy.DICT.lindiProjectType]"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey"
              >
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="money" label="项目金额">
            <a-input
                v-model="form.money"
                placeholder="请输入项目金额"
                style="width: 100%"
            />
          </a-form-item>

          <a-form-item field="tradeStatus" label="交易状态">
            <a-select
                v-model="form.tradeStatus"
                allow-clear
                placeholder="请选择交易状态"
            >
              <a-option
                  v-for="(item,index) in dicts[proxy.DICT.lindiTradeStatus]"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey"
              >
              </a-option>
            </a-select>
          </a-form-item>
        </div>

        <!-- 指标信息分组 -->
        <div class="form-section">
          <div class="form-section-title">指标信息</div>

          <a-form-item field="reserveArea" label="市储备库指标面积(亩)">
            <a-input
                v-model="form.reserveArea"
                placeholder="请输入市储备库指标面积"
                style="width: 100%"
            />
          </a-form-item>

          <a-form-item field="publicForestArea" label="省级公益林面积(亩)">
            <a-input
                v-model="form.publicForestArea"
                placeholder="请输入省级公益林面积"
                style="width: 100%"
            />
          </a-form-item>
        </div>

        <!-- 详细说明分组 -->
        <div class="form-section">
          <div class="form-section-title">详细说明</div>

          <a-form-item field="reason" label="购买理由">
            <a-textarea
                v-model="form.reason"
                :auto-size="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入购买理由"
            />
          </a-form-item>

          <a-form-item field="projectSituation" label="情况简介">
            <a-textarea
                v-model="form.projectSituation"
                :auto-size="{ minRows: 3, maxRows: 6 }"
                placeholder="请输入情况简介（体现土地四至以及备案号/立项项目编码/文件批复等）"
            />
          </a-form-item>
        </div>

        <!-- 文件上传分组 -->
        <div class="form-section">
          <div class="form-section-title">文件资料</div>

          <a-form-item field="redlineMapId" label="项目红线图">
            <div class="image-upload-container">
              <!-- 已有红线图展示区域 -->
              <div v-if="existingRedlineMap" class="existing-files-container mb-4">
                <div class="mb-2 flex items-center justify-between">
                  <div class="text-gray-500">
                    <icon-info-circle class="mr-1" /> 已上传红线图
                  </div>
                </div>
                <a-card class="file-card" hoverable>
                  <div class="flex items-start">
                    <div class="file-icon mr-3">
                      <a-avatar :size="40" shape="square">
                        <icon-file-image/>
                      </a-avatar>
                    </div>
                    <div class="flex-1 overflow-hidden">
                      <div class="font-medium truncate mb-1" :title="existingRedlineMap.fileName">{{ existingRedlineMap.fileName || '项目红线图' }}</div>
                      <div class="text-gray-500 text-xs mb-1">上传时间：{{ existingRedlineMap.createTime || '未知' }}</div>
                      <div class="text-gray-500 text-xs mb-2" v-if="existingRedlineMap.fileSize">文件大小：{{ formatFileSize(existingRedlineMap.fileSize) }}</div>
                      <div class="mt-2">
                        <a-space>
                          <a-button size="mini" type="primary" @click="downloadFile(existingRedlineMap)">
                            <template #icon>
                              <icon-download/>
                            </template>
                            下载
                          </a-button>
                          <a-button size="mini" @click="previewFile(existingRedlineMap)">
                            <template #icon>
                              <icon-eye/>
                            </template>
                            预览
                          </a-button>
                          <a-button size="mini" status="danger" @click="removeExistingRedlineMap">
                            <template #icon>
                              <icon-delete/>
                            </template>
                            删除
                          </a-button>
                        </a-space>
                      </div>
                    </div>
                  </div>
                </a-card>
              </div>
              
              <uploadFile
                  ref="redlineMapUploadFileRef"
                  :file-source="fs.redlineMap"
                  :limit="1"
                  :multiple="false"
                  accept=".jpg,.png,.jpeg"
                  list-type="picture"
                  source-type="proxy"
              />
            </div>
          </a-form-item>

          <a-form-item field="otherFiles" label="相关附件">
            <div class="file-upload-container">
              <!-- 已有附件展示区域 -->
              <div v-if="existingAttachments.length > 0" class="existing-files-container mb-4">
                <div class="mb-2 flex items-center justify-between">
                  <div class="text-gray-500">
                    <icon-info-circle class="mr-1" /> 已上传附件文件
                  </div>
                </div>
                <a-list :bordered="false" :grid="{ gutter: 16, column: 2, xs: 1, sm: 1, md: 2 }">
                  <a-list-item v-for="file in existingAttachments" :key="file.fileId">
                    <a-card class="file-card" hoverable>
                      <div class="flex items-start">
                        <div class="file-icon mr-3">
                          <a-avatar :size="40" shape="square">
                            <icon-file-pdf v-if="file.fileType === 'pdf' || file.fileType === 'application/pdf'"/>
                            <icon-file-image v-else-if="['jpg', 'png', 'jpeg', 'gif', 'bmp', 'webp', 'svg', 'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp', 'image/svg+xml'].includes(file.fileType)"/>
                            <icon-file v-else/>
                          </a-avatar>
                        </div>
                        <div class="flex-1 overflow-hidden">
                          <div class="font-medium truncate mb-1" :title="file.fileName">{{ file.fileName }}</div>
                          <div class="text-gray-500 text-xs mb-1">上传时间：{{ file.createTime || '未知' }}</div>
                          <div class="text-gray-500 text-xs mb-2" v-if="file.fileSize">文件大小：{{ formatFileSize(file.fileSize) }}</div>
                          <div class="mt-2">
                            <a-space>
                              <a-button size="mini" type="primary" @click="downloadFile(file)">
                                <template #icon>
                                  <icon-download/>
                                </template>
                                下载
                              </a-button>
                              <a-button size="mini" @click="previewFile(file)">
                                <template #icon>
                                  <icon-eye/>
                                </template>
                                预览
                              </a-button>
                              <a-button size="mini" status="danger" @click="removeExistingAttachment(file)">
                                <template #icon>
                                  <icon-delete/>
                                </template>
                                删除
                              </a-button>
                            </a-space>
                          </div>
                        </div>
                      </div>
                    </a-card>
                  </a-list-item>
                </a-list>
              </div>
              
              <uploadFile
                  ref="attachmentsUploadFileRef"
                  :file-source="fs.attachments"
                  :limit="5"
                  :multiple="true"
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg"
                  list-type="text"
                  source-type="proxy"
              />
              <div class="text-gray-400 text-xs mt-2">支持上传PDF、Word、Excel、图片等格式文件，最多5个</div>
            </div>
          </a-form-item>
        </div>
      </a-form>

      <!-- 按钮区域 -->
      <div class="action-buttons">
        <a-space>
          <a-button
              type="primary"
              @click="onSubmit"
          >
            提交
          </a-button>
          <a-button
              @click="onCancel"
          >
            取消
          </a-button>
        </a-space>
      </div>
    </div>
  </a-spin>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref, watch} from "vue";
import {addTradeApplicationApi, getTradeApplicationByTradeApplicationIdApi, updateTradeApplicationByTradeApplicationIdApi} from "~/api/lindi/tradeApplication.js";
import uploadFile from "~/components/uploadFile/index.vue";
import {fileSource} from "~/utils/sys.js";
import {getEnterpriseAccountListApi} from "~/api/lindi/enterpriseAccount.js";
import {IconInfoCircle, IconDownload, IconEye, IconDelete, IconFileImage, IconFilePdf, IconFile} from "@arco-design/web-vue/es/icon";

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emit
const emit = defineEmits(["ok", "cancel"]);

// 全局实例
const {proxy} = getCurrentInstance();

// 表单引用
const formRef = ref(null);
// 加载状态
const spinLoading = ref(false);
// 是否为编辑模式
const isEdit = ref(false);
// 已有红线图
const existingRedlineMap = ref(null);
// 已有附件列表
const existingAttachments = ref([]);
// 文件上传组件引用
const redlineMapUploadFileRef = ref(null);
const attachmentsUploadFileRef = ref(null);

// 文件源
const fs = {
  redlineMap: fileSource.lindi_redline_img?.key,
  attachments: fileSource.lindi_trade_attachment?.key
};

// 项目类型选项
const projectTypeOptions = [
  {value: 1, label: "项目占用林地"},
  {value: 2, label: "补充林地指标"},
];

// 表单数据
const form = reactive({
  tradeApplicationId: null,
  enterpriseAccountId: null,
  projectName: "",
  projectLocation: "",
  tradeStatus: null, // 交易状态
  tradeCode: "",
  reserveArea: "",  // 修改为字符串类型初始值
  publicForestArea: "",  // 修改为字符串类型初始值
  projectType: null,  // 项目类型
  money: "",  // 项目金额
  reason: "",  // 购买理由
  projectSituation: "",
  redlineMapId: null,
  redlineMapFile: null,
  otherFiles: [], // 附件ID列表
});

// 表单校验规则
const rules = {
  projectName: [
    {required: true, message: "项目名称不能为空"},
    {maxLength: 100, message: "项目名称长度不能超过100个字符"},
  ],
  projectLocation: [
    {required: true, message: "项目地址不能为空"},
    {maxLength: 200, message: "项目地址长度不能超过200个字符"},
  ],
  enterpriseAccountId: [
    {required: true, message: "请选择企业账号"},
  ],
};

// 提交表单
function onSubmit() {
  //表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      return false;
    }

    // 获取上传文件的ID
    form.redlineMapId = redlineMapUploadFileRef.value?.getUploadFileId() || null;

    // 获取附件ID列表
    const attachmentIds = attachmentsUploadFileRef.value?.getUploadFileId() || [];
    // 确保otherFiles是数组，并且每个元素都是单独的ID（不含逗号）
    if (Array.isArray(attachmentIds)) {
      // 处理数组中可能包含逗号分隔的ID字符串
      form.otherFiles = attachmentIds.flatMap(id => {
        if (typeof id === 'string' && id.includes(',')) {
          // 如果ID是包含逗号的字符串，拆分为多个ID
          return id.split(',').filter(Boolean);
        }
        return id;
      }).filter(Boolean);
    } else if (attachmentIds) {
      // 如果是单个ID或逗号分隔的ID字符串
      if (typeof attachmentIds === 'string' && attachmentIds.includes(',')) {
        form.otherFiles = attachmentIds.split(',').filter(Boolean);
      } else {
        form.otherFiles = [attachmentIds].filter(Boolean);
      }
    } else {
      form.otherFiles = [];
    }

    // 创建一个新对象用于提交，避免直接修改表单数据
    const submitData = {...form};

    // 如果后端需要数值类型，在这里转换
    if (submitData.reserveArea !== "") {
      submitData.reserveArea = Number(submitData.reserveArea);
    }

    if (submitData.publicForestArea !== "") {
      submitData.publicForestArea = Number(submitData.publicForestArea);
    }
    
    // 确保projectType是数字类型
    if (submitData.projectType !== null && submitData.projectType !== undefined) {
      // 由于在选择器中已经使用Number()转换，这里只是确保类型正确
      if (typeof submitData.projectType !== 'number') {
        submitData.projectType = Number(submitData.projectType);
      }
    }

    spinLoading.value = true;
    
    // 根据是否编辑模式选择API
    if (isEdit.value) {
      // 修改
      updateTradeApplicationByTradeApplicationIdApi(submitData)
          .then(() => {
            proxy.$message.success(proxy.operationType.update.success);
            emit("ok");
          })
          .catch((error) => {
            proxy.$message.error("修改交易申请失败: " + error.message);
          })
          .finally(() => {
            spinLoading.value = false;
          });
    } else {
      // 添加
      addTradeApplicationApi(submitData)
          .then(() => {
            proxy.$message.success(proxy.operationType.add.success);
            emit("ok");
          })
          .catch((error) => {
            proxy.$message.error("添加交易申请失败: " + error.message);
          })
          .finally(() => {
            spinLoading.value = false;
          });
    }
  });
}

// 取消
function onCancel() {
  emit("cancel");
}

// 企业列表
const enterpriseList = ref([]);

// 获取企业列表
function loadEnterpriseList() {
  getEnterpriseAccountListApi()
      .then((res) => {
        if (res) {
          enterpriseList.value = res;
        }
      })
      .catch((error) => {
        proxy.$message.error("加载企业列表失败: " + error.message);
      });
}

// 字典数据
const dicts = proxy.LoadDicts([proxy.DICT.lindiProjectType, proxy.DICT.lindiTradeStatus]);

// 下载文件
function downloadFile(file) {
  if (file.fileUrl) {
    window.open(file.fileUrl, '_blank');
  } else {
    proxy.$message.error('文件下载链接不存在');
  }
}

// 预览文件
function previewFile(file) {
  if (file.fileUrl) {
    window.open(file.fileUrl, '_blank');
  } else {
    proxy.$message.error('文件预览链接不存在');
  }
}

// 删除已有红线图
function removeExistingRedlineMap() {
  proxy.$modal.confirm({
    title: '确认删除',
    content: `确定要删除红线图 "${existingRedlineMap.value.fileName || '项目红线图'}" 吗？`,
    onOk: () => {
      // 清空红线图数据
      existingRedlineMap.value = null;
      form.redlineMapId = null;
      form.redlineMapFile = null;
      proxy.$message.success('红线图删除成功');
    }
  });
}

// 删除已有附件
function removeExistingAttachment(file) {
  proxy.$modal.confirm({
    title: '确认删除',
    content: `确定要删除附件 "${file.fileName}" 吗？`,
    onOk: () => {
      // 从已有附件列表中移除
      existingAttachments.value = existingAttachments.value.filter(item => item.fileId !== file.fileId);
      
      // 从表单的otherFiles中移除
      if (form.otherFiles && Array.isArray(form.otherFiles)) {
        form.otherFiles = form.otherFiles.filter(id => id !== file.fileId);
      }
      
      proxy.$message.success('附件删除成功');
    }
  });
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes || bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 监听参数变化
watch(
    () => props.params,
    () => {
      if (props.params.tradeApplicationId && props.params.operationType === proxy.operationType.update.type) {
        isEdit.value = true;
        loadTradeApplicationInfo(props.params.tradeApplicationId);
      } else {
        isEdit.value = false;
      }
    },
    {deep: true, immediate: true}
);

// 加载交易申请信息
function loadTradeApplicationInfo(tradeApplicationId) {
  spinLoading.value = true;

  getTradeApplicationByTradeApplicationIdApi(tradeApplicationId)
      .then(res => {
        if (res) {
          // 处理后端返回的数据
          const data = {...res};

          // 处理红线图
          if (data.redlineMapId) {
            // 设置红线图ID
            form.redlineMapId = data.redlineMapId;
            
            // 如果有红线图文件信息，设置到已有红线图
            if (data.redlineMapFile) {
              existingRedlineMap.value = data.redlineMapFile;
            }
          }

          // 处理其他附件列表
          if (data.otherFiles && Array.isArray(data.otherFiles) && data.otherFiles.length > 0) {
            existingAttachments.value = data.otherFiles;
          }

          // 将数据填充到表单
          Object.assign(form, data);
        } else {
          proxy.$message.error('获取交易申请详情失败');
        }
      })
      .catch(error => {
        proxy.$message.error('获取交易申请详情失败: ' + error.message);
      })
      .finally(() => {
        spinLoading.value = false;
      });
}

// 在组件挂载时加载企业列表
onMounted(() => {
  loadEnterpriseList();
});
</script>

<style scoped>
.edit-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 24px;
  max-width: 1000px;
  margin: 0 auto;
}

.edit-title {
  font-size: 18px;
  font-weight: 600;
  color: #1d4ed8;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
}

.edit-form {
  margin-bottom: 24px;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.form-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #4b5563;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #d1d5db;
}

.image-upload-container, .file-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 120px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  border: 1px dashed #d1d5db;
  padding: 16px;
  background-color: #ffffff;
}

.file-upload-container {
  min-height: 100px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

/* 已有附件展示样式 */
.existing-files-container {
  width: 100%;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e5e7eb;
}

.file-card {
  background-color: #f8fafc;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.file-card:hover {
  background-color: #f1f5f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.file-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .edit-container {
    padding: 16px;
  }

  .form-section {
    padding: 12px;
  }
}
</style>
